CREATE OR REPLACE FUNCTION reset_feature(character varying, character varying) RETURNS VOID AS '
DECLARE 
  vTableName ALIAS FOR $1;
  vFeatureName ALIAS FOR $2;
  curFeatureValues CURSOR (vfeatKeyId INTEGER) FOR 
      SELECT f.ft_int_value, f.ft_character_value, d.doc_url
         FROM t_feature f, t_document d
         WHERE d.doc_lr_id = f.ft_entity_id 
            AND f.ft_key_id = vfeatKeyId
         ORDER BY 1;

  vfeatureKeyId INTEGER = 0;
  vupdateStmt CHARACTER VARYING(4000);
  vfeatureIntValue INTEGER;
  vfeatureCharValue CHARACTER VARYING;
  vticketNumber CHARACTER VARYING;
BEGIN
    IF vTableName IS NULL OR trim(vTableName) = '''' THEN
        RAISE EXCEPTION ''First parameter "vTableName" is mandatory. Example: SELECT reset_feature(%, %);'', quote_literal(''ticketfeatures''), quote_literal(''leadticket'');
        EXIT;
    END IF;
    IF vFeatureName IS NULL OR trim(vFeatureName) = '''' THEN
        RAISE EXCEPTION ''Second parameter "vFeatureName" is mandatory. Example: SELECT reset_feature(%, %);'', quote_literal(''ticketfeatures''), quote_literal(''leadticket'');
        EXIT;
    END IF;
    SELECT min(k.fk_id) INTO vfeatureKeyId
        FROM t_feature_key k
        WHERE k.fk_string = vFeatureName;
    
    OPEN curFeatureValues(vfeatureKeyId);
    LOOP
        FETCH curFeatureValues INTO vfeatureIntValue, vfeatureCharValue, vticketNumber;
        IF  NOT FOUND THEN
            EXIT;  -- exit loop
        END IF;
        IF vfeatureIntValue IS NOT NULL
           OR (vfeatureCharValue  IS NOT NULL AND TRIM(vfeatureCharValue) != '''') THEN

            vticketNumber := substring(vticketNumber from (char_length(vticketNumber) - 13) for 10);
            vupdateStmt := ''UPDATE '' || quote_ident(vTableName) || '' SET '' || vFeatureName || '' = '';

            IF vfeatureIntValue IS NOT NULL THEN
                vupdateStmt := vupdateStmt || vfeatureIntValue;
            ELSE
                vupdateStmt := vupdateStmt || quote_literal(vfeatureCharValue);
            END IF;

            vupdateStmt := vupdateStmt || '' WHERE TicketNumber = '' || quote_literal(vticketNumber) || '';'';
            EXECUTE vupdateStmt;
            RAISE NOTICE ''%'', vupdateStmt;
        ELSE
            vticketNumber := substring(vticketNumber from (char_length(vticketNumber) - 13) for 10);
            vupdateStmt := ''UPDATE '' || quote_ident(vTableName) || '' SET '' || vFeatureName || '' = null '';
            vupdateStmt := vupdateStmt || '' WHERE TicketNumber = '' || quote_literal(vticketNumber) || '';'';
            EXECUTE vupdateStmt;
            --RAISE NOTICE ''%'', vupdateStmt;
        END IF;
    END LOOP;
    CLOSE curFeatureValues;
END;
' LANGUAGE 'plpgsql';


-- SELECT reset_feature('');

